package site.teamo.biu.net.common.web.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import site.teamo.biu.net.common.constant.HttpHeader;
import site.teamo.biu.net.common.web.configuration.PassportConfiguration;
import site.teamo.biu.net.common.web.constant.ResponseCode;
import site.teamo.biu.net.common.web.controller.model.passport.ChangePasswordRequest;
import site.teamo.biu.net.common.web.controller.model.passport.LoginRequest;
import site.teamo.biu.net.common.web.service.PassportService;
import site.teamo.biu.tool.core.cache.SessionCache;
import site.teamo.biu.tool.core.model.BiuJSONResult;
import site.teamo.biu.tool.core.util.BiuJSONResultUtils;
import site.teamo.biu.tool.core.util.CaptchaFactory;
import site.teamo.biu.tool.spring.annotation.Validation;

/**
 * @author haocongshun
 * @date 2023/02/22 11:00:39
 */
@Tag(name = "界面认证")
@RestController
@RequestMapping("/api/passport")
@CrossOrigin
public class PassportController {

    @Resource
    private SessionCache<String> sessionCache;

    @Resource
    private CaptchaFactory captchaFactory;

    @Resource(name = "passportServiceImpl")
    private PassportService passportService;

    @Operation(summary = "生成一个验证码")
    @GetMapping("/generate-captcha")
    public BiuJSONResult<CaptchaFactory.CaptchaImage> generateCaptcha() {
        CaptchaFactory.CaptchaImage captcha = captchaFactory.createCaptcha();
        return BiuJSONResultUtils.ok(captcha);
    }

    @Operation(summary = "管理界面登录")
    @PostMapping("/login")
    public BiuJSONResult<String> login(@RequestBody LoginRequest request) {
        if (!captchaFactory.verify(request.getCaptchaId(), request.getCaptchaCode())) {
            return BiuJSONResultUtils.error(ResponseCode.CAPTCHA_ERROR);
        }
        if (!passportService.verifyPassword(request.getPassword())) {
            return BiuJSONResultUtils.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        String sessionToken = sessionCache.login(PassportConfiguration.USERNAME);
        return BiuJSONResultUtils.ok(sessionToken);
    }


    @Operation(summary = "登录界面退出")
    @PostMapping("/logout")
    public BiuJSONResult<Object> logout(@RequestHeader(value = HttpHeader.ACCESS_TOKEN) String accessToken) {
        sessionCache.logout(accessToken);
        return BiuJSONResultUtils.ok();
    }


    @Operation(summary = "修改管理员密码")
    @PostMapping("/change-password")
    @Validation
    public BiuJSONResult<Boolean> changePassword(@RequestBody ChangePasswordRequest request) {
        boolean flag = passportService.changePassword(request.getOldPassword(), request.getNewPassword());
        return BiuJSONResultUtils.ok(flag);
    }

}
